package com.ziyueyuwen.xiniao.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suyeer.basic.util.EncryptUtil;
import com.suyeer.basic.util.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Date;

import static com.suyeer.basic.util.ConstUtil.CONTENT_TYPE_APPLICATION_JSON;
import static com.ziyueyuwen.xiniao.util.ConstUtil.SYS_CONFIG_DATA;

/**
 * @author jun 2019/3/8
 */
public class TangLangUtil {

    private final static String TANG_LONG_KEY = SYS_CONFIG_DATA.getTangLangKey();
    private final static Integer TANG_LONG_COMPANY_ID = SYS_CONFIG_DATA.getTangLangCompanyId();
    private final static String TANG_LONG_URL_PREFIX = SYS_CONFIG_DATA.getTangLangUrlPrefix();

    /**
     * 测试环境
     */
//    private final static String TANG_LONG_KEY = "test0805MtsApi10";
//    private final static Integer TANG_LONG_COMPANY_ID = 6114;
//    private final static String TANG_LONG_URL_PREFIX = "http://118.31.112.168:17000/api/ShiXinBasisCon";


    /**
     * 线上环境
     */
//    private final static String TANG_LONG_KEY = "ziyuemantis0311mtsApi";
//    private final static Integer TANG_LONG_COMPANY_ID = 3016;
//    private final static String TANG_LONG_URL_PREFIX = "http://api.n4.bjmantis.net/api/ZiYueCustomerCon";
    public static void main(String[] args) {
        try {
            addCustomer("18744763356", "周丹", "二年级", "转介绍");
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }

    /**
     * 获取基础信息接口
     *
     * @return JSONObject
     * @throws Exception Exception
     */
    public static JSONObject queryBaseList() throws Exception {
        JSONObject params = initParams();
        JSONObject retObj = sendRequestToTangLang(TANG_LONG_URL_PREFIX + "/queryBaseList", params);
        LogUtil.info(JSON.toJSONString(retObj));
        return retObj;
    }

    /**
     * 添加客户到螳螂
     *
     * @param customerPhoneNum String
     * @param ownerName        String
     * @return JSONObject
     * @throws Exception Exception
     */
    public static JSONObject addCustomer(String customerPhoneNum, String ownerName, String classLevel, String sourceType) throws Exception {
        JSONObject params = initParams();
        params.put("phone", customerPhoneNum);
        params.put("seaName", "北京");
        params.put("courseName", "小班直播课");
        params.put("buName", "子曰语文");
        params.put("ownerId", ownerName);
        params.put("content", classLevel);
        params.put("sourceType", sourceType);
        JSONObject retObj = sendRequestToTangLang(TANG_LONG_URL_PREFIX + "/insertCustomer", params);
        if (retObj != null && StringUtils.isNotBlank(retObj.getString("message"))) {
            LogUtil.error(JSON.toJSONString(retObj));
        } else {
            LogUtil.info(JSON.toJSONString(retObj));
        }
        return retObj;
    }

    /**
     * 从螳螂读取用户信息
     *
     * @param startDate Date
     * @param endDate   Date
     * @return JSONObject
     * @throws Exception Exception
     */
    public static JSONObject listUserInfoFromTangLang(Date startDate, Date endDate) throws Exception {
        String startTime = com.suyeer.basic.util.DateUtil.getDateStr(startDate);
        String endTime = com.suyeer.basic.util.DateUtil.getDateStr(endDate);
        JSONObject tangLangParams = initParams();
        tangLangParams.put("startTime", startTime);
        tangLangParams.put("endTime", endTime);
        return sendRequestToTangLang(TANG_LONG_URL_PREFIX + "/queryCustomerList", tangLangParams);
    }

    private static JSONObject initParams() {
        JSONObject params = new JSONObject();
        Long time = System.currentTimeMillis();
        String token = EncryptUtil.md5(TANG_LONG_KEY + time);
        params.put("companyId", TANG_LONG_COMPANY_ID);
        params.put("time", time);
        params.put("token", token.toLowerCase());
        return params;
    }

    public static JSONObject sendRequestToTangLang(String url, JSONObject params) {
        LogUtil.info(url);
        LogUtil.info(JSON.toJSONString(params));
        JSONObject retObj = null;
        CloseableHttpClient httpClient = null;

        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setConfig(getRequestConfig());
            StringEntity entity = new StringEntity(params.toJSONString(), ContentType.create(CONTENT_TYPE_APPLICATION_JSON, "UTF-8"));
            httpPost.setEntity(entity);
            retObj = sendRequest(httpClient, httpPost);
        } catch (Exception e) {
            LogUtil.error("POST请求失败,URL: {}, Message: {}", url, e.getMessage());
        } finally {
            closeHttpClient(httpClient);
        }

        return retObj;
    }

    private static JSONObject sendRequest(CloseableHttpClient chc, HttpUriRequest hur) throws Exception {
        CloseableHttpResponse response = chc.execute(hur);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new Exception("请求返回状态异常,状态码: " + statusCode);
        } else {
            return JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
        }
    }

    private static RequestConfig getRequestConfig() {
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .setConnectionRequestTimeout(10000)
                .build();
        return defaultRequestConfig;
    }

    private static void closeHttpClient(CloseableHttpClient chc) {
        if (chc != null) {
            try {
                chc.close();
            } catch (IOException e) {
                LogUtil.error("httpClient对象关闭异常: {}", e.getMessage());
            }
        }
    }
}
